/**
 * 初始化详情对话框
 */
var ReceiveBasicInformationInfoDlg = {
    receiveBasicInformationInfoData : {}
};



/**
 * 关闭此对话框
 */
ReceiveBasicInformationInfoDlg.close = function() {
    parent.layer.close(window.parent.ReceiveBasicInformation.layerIndex);
}

function test(){
	
	var isFine = true;
	
	if($("#receiveStartDate").val()==""){
		alert("起运日期不能为空！");
		$("#receiveStartDate").focus();
		isFine = false;
		return isFine;
	}
	
	if($("#receiveArrivalDate").val()==""){
		alert("到货日期不能为空！");
		$("#receiveArrivalDate").focus();
		isFine = false;
		return isFine;
	}
	
	if($("#receiveConsigner").val()==""){
		alert("发货人不能为空！");
		$("#receiveConsigner").focus();
		isFine = false;
		return isFine;
	}
	
	
	
	if($("#receiveConsignerTell").val()==""){
		alert("发货人电话不能为空！");
		$("#receiveConsignerTell").focus();
		isFine = false;
		return isFine;
	}
	if($("#receiveConsignerPlace").val()==""){
		alert("发货人地址不能为空！");
		$("#receiveConsignerPlace").focus();
		isFine = false;
		return isFine;
	}
	
	if($("#receiveConsignee").val()==""){
		alert("收货人不能为空！");
		$("#receiveConsignee").focus();
		isFine = false;
		return isFine;
	}
	
	if($("#receiveConsigneeTell").val()==""){
		alert("收货人电话不能为空！");
		$("#receiveConsigneeTell").focus();
		isFine = false;
		return isFine;
	}
	if($("#receiveConsigneePlace").val()==""){
		alert("收货人地址不能为空！");
		$("#receiveConsigneePlace").focus();
		isFine = false;
		return isFine;
	}
	if($("#receiveShippingMethod").val()==""){
		alert("送货方式不能为空！");
		$("#receiveConsigneePlace").focus();
		isFine = false;
		return isFine;
	}
	
	$("input[name='receiveGoodsName']").each(function(){
		
		if($(this).val()==""){
			alert("货物名不能为空！");
			isFine = false;
			return isFine;
		}
	});
	

	$("input[name='receiveGoodsQuantity']").each(function(){
		
		if($(this).val()==""||$(this).val()=="0"){
			alert("数量不能为空或0！");
			isFine = false;
			return isFine;
		}
	});
	
	
$("input[name='receiveGoodsWeight']").each(function(){
		
		if($(this).val()==""){
			alert("重量不能为空！");
			isFine = false;
			return isFine;
		}
	});

$("input[name='receiveGoodsVolume']").each(function(){
	
	if($(this).val()==""){
		alert("体积不能为空！");
		isFine = false;
		return isFine;
	}
});
	
	
	$("input[name='receiveGoodsFreight']").each(function(){
			
			if($(this).val()==""){
				alert("运费不能为空！");
				isFine = false;
				return isFine;
			}
		});
	$("input[name='receiveGoodsMessagefee']").each(function(){
		
		if($(this).val()==""){
			alert("信息费不能为空！");
			isFine = false;
			return isFine;
		}
	});
	
	$("input[name='receiveGoodsPickupCharge']").each(function(){
		
		if($(this).val()==""){
			alert("提货费不能为空！");
			isFine = false;
			return isFine;
		}
	});
	
	$("input[name='receiveGoodsPackage']").each(function(){
			
			if($(this).val()==""){
				alert("包装方式不能为空！");
				isFine = false;
				return isFine;
			}
		});
	
	$("input[name='receiveGoodsWarehouseName']").each(function(){
		
		if($(this).val()==""){
			alert("仓库不能为空！");
			isFine = false;
			return isFine;
		}
	});
	
	//判断物品号是否重复
	var ary = new Array();
	var i = 0;
	$("input[name='receiveGoodsId']").each(function(){
		ary[i] = $(this).val();
		i++;
	});
	var nary = ary.sort();
	
	for(var i=0;i<ary.length;i++){

		if (nary[i]==nary[i+1]){

		alert("货物不能重复！");
		isFine = false;
		return;
		}
	} 
	return isFine;

}

//数据初始化，验证封装
$(function() {
	
});

/**
 * 提交添加
 */

//form序列化，转成单个json对象
$.fn.serializeObject = function()    
{    
   var o = {};    
   var a = this.serializeArray();    
   $.each(a, function() {    
       if (o[this.name]) {    
           if (!o[this.name].push) {    
               o[this.name] = [o[this.name]];    
           }    
           o[this.name].push(this.value || '');    
       } else {    
           o[this.name] = this.value || '';    
       }    
   });    
   return o;    
};  

//form序列化，转成json的list
$.fn.serializeJson = function(){
    var jsonData1 = {};
    var serializeArray = this.serializeArray();
    // 先转换成{"id": ["12","14"], "name": ["aaa","bbb"], "pwd":["pwd1","pwd2"]}这种形式
    $(serializeArray).each(function () {
        if (jsonData1[this.name]) {
            if ($.isArray(jsonData1[this.name])) {
                jsonData1[this.name].push(this.value);
            } else {
                jsonData1[this.name] = [jsonData1[this.name], this.value];
            }
        } else {
            jsonData1[this.name] = this.value;
        }
    });
    // 再转成[{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name": "bb", "pwd":"pwd2"}]的形式
    var vCount = 0;
    // 计算json内部的数组最大长度
    for(var item in jsonData1){
        var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1;
        vCount = (tmp > vCount) ? tmp : vCount;
    }

    if(vCount > 1) {
        var jsonData2 = new Array();
        for(var i = 0; i < vCount; i++){
            var jsonObj = {};
            for(var item in jsonData1) {
                jsonObj[item] = jsonData1[item][i];
            }
            jsonData2.push(jsonObj);
        }
        return JSON.stringify(jsonData2);
    }else{
        return "[" + JSON.stringify(jsonData1) + "]";
    }
};

/**
 * 提交修改
 */
ReceiveBasicInformationInfoDlg.editSubmit = function() {
	
	if(test()==true){

		var modelReceive ={};
		modelReceive.consignerID = $("#consignerID").val();
		modelReceive.consigneeID = $("#consigneeID").val();
		var jsonArray = JSON.parse($("#goodsInfo").serializeJson());
		modelReceive.receiveBasicInformation  =  $('#receiveContract').serializeObject();
		modelReceive.receiveGoodsInformations = jsonArray;
		var jsonData = JSON.stringify(modelReceive);
		
	    $.ajax({
			async : false,
			type : 'post',
			url : Feng.ctxPath+'/receiveBasicInformation/update',
			contentType : "application/json;charset=UTF-8",
			data :jsonData,
			success : function(data) {
				if (data == 'SUCCESS') {
					Feng.success("修改成功!");
			        window.parent.ReceiveBasicInformation.table.refresh();
			        ReceiveBasicInformationInfoDlg.close();
				} else if(data == 'FAIL'){
					 Feng.error("修改失败，该合同已经通过审核！");
				}
			},
			error : function(data) {
				 Feng.error("修改失败!");
			}
		});
		
	}

}

ReceiveBasicInformationInfoDlg.addSubmit = function() {
	
	if(test()==true){
		var modelReceive ={};
		modelReceive.consignerID = $("#consignerID").val();
		modelReceive.consigneeID = $("#consigneeID").val();
		var jsonArray = JSON.parse($("#goodsInfo").serializeJson());
		modelReceive.receiveBasicInformation  =  $('#receiveContract').serializeObject();
		modelReceive.receiveGoodsInformations = jsonArray;
		var jsonData = JSON.stringify(modelReceive);
		
		console.log(jsonData);
		
	    $.ajax({
			async : false,
			type : 'post',
			url : Feng.ctxPath+'/receiveBasicInformation/add',
			contentType : "application/json;charset=UTF-8",
			data :jsonData,
			success : function(data) {
				if (data == 'SUCCESS') {
					Feng.success("添加成功!");
			        window.parent.ReceiveBasicInformation.table.refresh();
			        ReceiveBasicInformationInfoDlg.close();
				} else {
					 Feng.error("添加失败!" + data.responseJSON.message + "!");
				}
			},
			error : function(data) {
				 Feng.error("添加失败!" + data.responseJSON.message + "!");
			}
		});
	}
}


var timer="";
//获取发货人信息的下拉框
$("#receiveConsigner").bind("keyup click",function(){
	//获取发货人姓名
	var consigner = $("#receiveConsigner").val();
	//显示下拉框
	var pName = $("#receiveConsigner");
    var pNameOffset = $("#receiveConsigner").offset();
    
  //清空发货人标志
    $("#consignerID").val("");
    
    //发货人住址、电话信息，重新按下按键时 清空数据初始化
     $("#receiveConsignerTell").val("");
     $("#receiveConsignerPlace").val("");
     $("#receiveConsignerTell").removeAttr("readOnly")
     $("#receiveConsignerPlace").removeAttr("readOnly")
      $("#receiveConsignerTell").css('background-color','');
     $("#receiveConsignerPlace").css('background-color','');
    
   

//    $("body").bind("mousedown", onBodyDown);
    
    clearTimeout(timer);
  	//清空查询信息
  	$("#show-Consigner").empty();
  	
  	
  	timer = setTimeout(function(){
      $.ajax({
             url: Feng.ctxPath + '/consigner/listbyname', 
             type: "POST",
                data :{"consigner":consigner} ,
             dataType:"json",
             success:function(data){
	          	   var consigners = data;
	          	   if(JSON.stringify(consigners) === '[]'){
	          		 $("#showConsigner").css({
	            	        left : pNameOffset.left + "px",
	            	        top : pNameOffset.top + pName.outerHeight() + "px"
	            	    }).hide();
	          	   }else{
	          		 for(i in consigners){
	          			 var index = parseInt(i)+1;
	                     var $li = $("<li class='XX'></li>");
	                     var consigner = consigners[i];
	                     $li.text(index+"."+consigner.consignerName);
	                     $("#show-Consigner").append($li);
	                 }       
	            	 $("#showConsigner").css({
	            	        left : pNameOffset.left + "px",
	            	        top : pNameOffset.top + pName.outerHeight() + "px"
	            	    }).show();
	
	                 $("#show-Consigner li.XX").each(function(){
	                       $(this).click(function(){
	                            $("#receiveConsigner").val($(this).text().split(".")[1]);
	                            var id =parseInt($(this).text().split(".")[0])-1;
	                            $("#receiveConsignerTell").val(consigners[id].consignerMobile);
	                            $("#receiveConsignerTell").attr("readonly","readonly");
	                            $("#receiveConsignerTell").css('background-color','#eee');
	                            $("#receiveConsignerPlace").val(consigners[id].consignerPlace);
	                            $("#receiveConsignerPlace").attr("readonly","readonly");
	                            $("#receiveConsignerPlace").css('background-color','#eee');
	                            //表明数据是从数据库中而来
	                            $("#consignerID").val("yes");
	                            $("#showConsigner").css({
	    	            	        left : pNameOffset.left + "px",
	    	            	        top : pNameOffset.top + pName.outerHeight() + "px"
	    	            	    }).hide();
	                       });
	                   });
	          	   }
             }
          });},10);
  });

//获取收货人信息的下拉框
$("#receiveConsignee").bind("keyup click",function(){
	//获取发货人姓名
	var consignee = $("#receiveConsignee").val();
	//显示下拉框
	var peName = $("#receiveConsignee");
    var peNameOffset = $("#receiveConsignee").offset();
    
  //清空发货人标志
    $("#consigneeID").val("");
    
    //发货人住址、电话信息，重新按下按键时 清空数据初始化
     $("#receiveConsigneeTell").val("");
     $("#receiveConsigneePlace").val("");
     $("#receiveConsigneeTell").removeAttr("readOnly")
     $("#receiveConsigneePlace").removeAttr("readOnly")
      $("#receiveConsigneeTell").css('background-color','');
     $("#receiveConsigneePlace").css('background-color','');
    
   

//    $("body").bind("mousedown", onBodyDown);
    
    clearTimeout(timer);
  	//清空查询信息
  	$("#show-Consignee").empty();
  	
  	timer = setTimeout(function(){
      $.ajax({
             url: Feng.ctxPath + '/consignee/listbyname', 
             type: "POST",
                data :{"consignee":consignee} ,
             dataType:"json",
             success:function(data){
	          	   var consignees = data;
	          	   if(JSON.stringify(consignees) === '[]'){
	          		 $("#showConsignee").css({
	            	        left : peNameOffset.left + "px",
	            	        top : peNameOffset.top + peName.outerHeight() + "px"
	            	    }).hide();
	          	   }else{
	          		 for(i in consignees){
	          			 var index = parseInt(i)+1;
	                     var $li = $("<li class='XX'></li>");
	                     var consignee = consignees[i];
	                     $li.text(index+"."+consignee.consigneeName);
	                     $("#show-Consignee").append($li);
	                 }       
	            	 $("#showConsignee").css({
	            	        left : peNameOffset.left + "px",
	            	        top : peNameOffset.top + peName.outerHeight() + "px"
	            	    }).show();
	
	                 $("#show-Consignee li.XX").each(function(){
	                       $(this).click(function(){
	                            $("#receiveConsignee").val($(this).text().split(".")[1]);
	                            var id =parseInt($(this).text().split(".")[0])-1;
	                            $("#receiveConsigneeTell").val(consignees[id].consigneeMobile);
	                            $("#receiveConsigneeTell").attr("readonly","readonly");
	                            $("#receiveConsigneeTell").css('background-color','#eee');
	                            $("#receiveConsigneePlace").val(consignees[id].consigneePlace);
	                            $("#receiveConsigneePlace").attr("readonly","readonly");
	                            $("#receiveConsigneePlace").css('background-color','#eee');
	                            //表明数据是从数据库中而来
	                            $("#consigneeID").val("yes");
	                            $("#showConsignee").css({
	    	            	        left : peNameOffset.left + "px",
	    	            	        top : peNameOffset.top + peName.outerHeight() + "px"
	    	            	    }).hide();
	                       });
	                   });
	          	   }
             }
          });},10);
  });
$("body").click(function(){
	//发货人模块
	var pName = $("#receiveConsigner");
    var pNameOffset = $("#receiveConsigner").offset();
	$("#showConsigner").css({
        left : pNameOffset.left + "px",
        top : pNameOffset.top + pName.outerHeight() + "px"
    }).hide();
	
	//收货人模块
	var peName = $("#receiveConsignee");
    var peNameOffset = $("#receiveConsignee").offset();
	$("#showConsignee").css({
        left : peNameOffset.left + "px",
        top : peNameOffset.top + peName.outerHeight() + "px"
    }).hide();
	
	//货物信息模块
	$("#showGoods").css({
        left : peNameOffset.left + "px",
        top : peNameOffset.top + peName.outerHeight() + "px"
    }).hide();
});


//查询商品信息操作，只允许点击一次
$("body").on("keyup click","[name='receiveGoodsName']",function(){ 
	
	var goodN = $(this);
	var goodsName = $(this).val();
	//获取标志位，该input标志该数据是否是从数据库中取出的
	var goodsID = $(this).parent().siblings().eq(1);
	var receiveGoodsId =  $(this).parent().siblings().eq(2).children().first();
	var goodsModel = $(this).parent().siblings().eq(3).children().first();
	var goodsPackage = $(this).parent().siblings().eq(4).children().first();
	var warehouseName = $(this).parent().siblings().eq(11).children().first();
	
	
	//显示下拉框
	var pfName = $(this);
    var pfNameOffset = $(this).offset();
    
	 clearTimeout(timer);
	  	//清空查询信息
	  	$("#show-Goods").empty();
	  	
	  	timer = setTimeout(function(){
	      $.ajax({
	             url: Feng.ctxPath + '/goods/listbyname', 
	             type: "POST",
	                data :{"goodsName":goodsName} ,
	             dataType:"json",
	             success:function(data){
		          	   var goods = data;
		          	   if(JSON.stringify(goods) === '[]'){
		          		 $("#showGoods").css({
		            	        left : pfName.left + "px",
		            	        top : pfNameOffset.top + pfName.outerHeight() + "px"
		            	    }).hide();
		          	   }else{
		          		 for(i in goods){
		          			 var index = parseInt(i)+1;
		                     var $li = $("<li class='XX'></li>");
		                     var good = goods[i];
		                     $li.text(index+"."+good.goodsName);
		                     $("#show-Goods").append($li);
		                 }       
		            	 $("#showGoods").css({
		            	        left : pfNameOffset.left + "px",
		            	        top : pfNameOffset.top + pfName.outerHeight() + "px"
		            	    }).show();
		
		                 $("#show-Goods li.XX").each(function(){
		                       $(this).click(function(){
		                    	   //货物名固定
		                    	   goodN.val($(this).text().split(".")[1]);
		                    	   goodN.attr("readonly","readonly");
		                    	   goodN.css('background-color','#eee');
		                            var id =parseInt($(this).text().split(".")[0])-1;
		                            //标志位初始化
		                            goodsID.val("yes");
		                            //货物编号固定
		                            receiveGoodsId.val(goods[id].goodsId);
		                            receiveGoodsId.attr("readonly","readonly");
		                            receiveGoodsId.css('background-color','#eee');
		                            
		                            //规格型号固定
		                            goodsModel.val(goods[id].goodsModel);
		                            goodsModel.attr("readonly","readonly");
		                            goodsModel.css('background-color','#eee');
		                            //包装方式固定
		                            goodsPackage.val(goods[id].goodsPackage);
		                            
		                            //仓库信息固定
		                            warehouseName.val(goods[id].goodsWarehouse);
		                            
		                          
		                            $("#showGoods").css({
		    	            	        left : pfNameOffset.left + "px",
		    	            	        top : pfNameOffset.top + pfName.outerHeight() + "px"
		    	            	    }).hide();
		                       });
		                   });
		          	   }
	             }
	          });},10);
});

